import {isNull} from "@utils/stringUtil.ts";

class DataStorage {
    expiration: Date;
    date: any;

    constructor(data: any) {
        this.expiration = new Date();
        this.date = data
    }
}

export function saveData(dataName: string, data: any) {
    if (isNull(dataName)) return
    if (isNull(data)) {
        localStorage.removeItem(dataName);
        return;
    }
    localStorage.setItem(data, JSON.stringify(new DataStorage(data)));
}

export function getData(tokenName: string) {
    if (isNull(tokenName)) return null;
    try {
        const str = localStorage.getItem(tokenName);
        if (isNull(str)) {
            localStorage.removeItem(tokenName);
            return null;
        }
        if (typeof str !== "string") {
            localStorage.removeItem(tokenName);
            return null
        }
        const data: DataStorage = JSON.parse(str);

        if (data.expiration && (Date.now() - new Date(data.expiration).getTime())>=1000*60*60*10) {
            localStorage.removeItem(tokenName);
            return null
        }
        return data.date;
    } catch (e) {
        localStorage.removeItem(tokenName);
        return null;
    }
}


export function delToken(tokenName: string) {
    if (isNull(tokenName)) return
    localStorage.removeItem(tokenName);
}
